package com.d3works.apps.account.db.repo;

import com.d3works.apps.account.db.AccountingSituation;
import com.d3works.apps.account.service.AccountingSituationInitService;
import com.d3works.apps.base.db.Partner;
import com.d3works.apps.base.db.repo.PartnerBaseRepository;
import com.d3works.apps.base.service.app.AppService;
import com.d3works.exception.service.TraceBackService;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import javax.persistence.PersistenceException;
import org.apache.commons.collections.CollectionUtils;

@Singleton
public class PartnerAccountRepository extends PartnerBaseRepository {

  private AppService appService;

  private AccountingSituationInitService accountingSituationInitService;

  @Inject
  public PartnerAccountRepository(
      AppService appService, AccountingSituationInitService accountingSituationInitService) {
    this.appService = appService;
    this.accountingSituationInitService = accountingSituationInitService;
  }

  @Override
  public Partner save(Partner partner) {
    try {

      if (partner.getId() == null) {
        partner = super.save(partner);
      }

      if (appService.isApp("account")) {
        if (!partner.getIsContact() || partner.getIsEmployee()) {
          // Create & fill
          accountingSituationInitService.createAccountingSituation(this.find(partner.getId()));
        }

        // We do this for contacts too as it seems this is the way employees are handled
        if (CollectionUtils.isNotEmpty(partner.getAccountingSituationList())) {
          for (AccountingSituation situation : partner.getAccountingSituationList()) {
            accountingSituationInitService.createPartnerAccounts(situation);
          }
        }
      }

      return super.save(partner);
    } catch (Exception e) {
      TraceBackService.traceExceptionFromSaveMethod(e);
      throw new PersistenceException(e.getMessage(), e);
    }
  }

  @Override
  public Partner copy(Partner partner, boolean deep) {

    Partner copy = super.copy(partner, deep);

    if (appService.isApp("account")) {
      copy.setAccountingSituationList(null);
    }

    return copy;
  }
}
